package com.hm.health.records;

import android.util.Log;

import com.goodix.comsdk.entity.MeasureResult;
import com.goodix.comsdk.sdk.OnHBDDataListener;
import com.goodix.iot.libbase.logger.Glog;
import com.goodix.libromablecom.sdk.cardiff.CardiffConstants;
import com.goodix.libromablecom.sdk.cardiff.arguments.StartArgumentsKeyEnum;
import com.goodix.utils.SPUtils;
import com.goodix.utils.TimeUtil;
import com.google.gson.reflect.TypeToken;
import com.hm.health.MyApplication;
import com.hm.health.Utils.TimeUtils;
import com.hm.health.entity.BleDevicesInfo;
import com.hm.health.entity.dao.EcgStatistics;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenshi on 2020/3/16.
 */

public class EcgTestRecord implements ITestRecord{
    public static final String TAG = "EcgTestRecord";
    private EcgStatistics mStatistics;
    private LostPacketStatistics mLostPacketStatistics;
    private String mStartTime;
    private ArrayList<Integer> mDatas = new ArrayList<>();
    private ArrayList<Integer> mHrdatas = new ArrayList<>();
    private List<BleDevicesInfo> mBleDeviceInfos;
    private boolean mFindFirstGreaterThanZeroHr = false;
    private long mStartTimel = 0;

    @Override
    public void startSaveRecord(String startTime, String testerInfo,
                                List<BleDevicesInfo> devicesInfos) {
        mBleDeviceInfos = devicesInfos;
        mStatistics = new EcgStatistics();
        mStatistics.setStartTime(startTime);
        mStatistics.setTesterName(testerInfo);
        mStartTime = startTime;
        mStartTimel = TimeUtil.getTime(mStartTime);
        mStatistics.setFrequence(500);
        mFindFirstGreaterThanZeroHr = false;
        mLostPacketStatistics = new LostPacketStatistics();
        mLostPacketStatistics.init(MyApplication.getHBDTestClient(), 255);
        mLostPacketStatistics.startDetection();
        MyApplication.getHBDTestClient().registerHBDDataListener(mOnHBDDataListener);
    }

    @Override
    public void stopSaveRecord() {
        MyApplication.getHBDTestClient().unRegisterHBDDataListener(mOnHBDDataListener);

        if (System.currentTimeMillis() - mStartTimel < 30 * 1000) {
            Glog.d(TAG, "ecg measurement duration should more than 30 seconds");
            return;
        }

        mStatistics.setDuration(TimeUtils.timeDifference(TimeUtil.getTime(mStartTime),
                System.currentTimeMillis()));

        if (mDatas.size() < 1000) {
            Glog.d(TAG, "mDatas is empty~");
            return;
        }

        // 删除前1000个点
        for (int i = 0; i < 1000; ++i) {
            mDatas.remove(0);
        }

        SPUtils.putJsonObj(MyApplication.getContext(), mStartTime, mDatas,
                new TypeToken<List<Integer>>(){}.getType());

        mStatistics.setEcgRawdataPath(mStartTime);

        // 计算心率均值
        if (mHrdatas.size() > 0) {
            long sum = 0;
            for (Integer v : mHrdatas) {
                sum += v;
            }
            int hrAverage = (int) (sum / mHrdatas.size());
            mStatistics.setHrAverage(hrAverage);
        }

        if (null != mLostPacketStatistics) {
            mLostPacketStatistics.stopDetection();
            mStatistics.setTotalPacketsCount(mLostPacketStatistics.getTotalPackets());
            mStatistics.setLostPacketsCount(mLostPacketStatistics.getLostPacketCount());
        }

        boolean ret = mStatistics.save();
        Log.i(TAG, "stopSaveRecord: ret:" + ret);
    }

    @Override
    public void onMeasureResult(List<MeasureResult> results) {

    }

    private volatile  boolean clearData = true;
    private OnHBDDataListener mOnHBDDataListener = new OnHBDDataListener() {
        @Override
        public void onDataChanged(String dataType, int[] dataArr) {
            if (dataType.equals(StartArgumentsKeyEnum.AppFunction_ECG)) {
                if((dataArr[CardiffConstants.RawdataColumn.FLAG2.ordinal()] & 2) == 2) {
                    clearData = true;
                    mDatas.clear();
                    mStartTimel = System.currentTimeMillis();
                }
                if (mDatas.size() <= 32 * 500) {
                    mDatas.add(dataArr[CardiffConstants.RawdataColumn.ALGO_RESULT0.ordinal()]);
                }
            } else if (dataType.equals(StartArgumentsKeyEnum.ALG_ECG_CLASSIFICATION_RESULT)) {
                mStatistics.setPathologicalInformation(dataArr[0]);
            }
        }

        @Override
        public void onMeasureResult(MeasureResult result) {
            // GHealth HR
            if (result.getDeviceAddress().equals(mBleDeviceInfos.get(0).getDeviceAddress())
                    && result.getFunctionName().equals(StartArgumentsKeyEnum.AppFunction_ECG)
                    && result.getTitle().equals(StartArgumentsKeyEnum.AppFunction_HR)) {
                if (clearData) {
                    mHrdatas.clear();
                }

                if (result.getIntValue() > 0) {
                    mFindFirstGreaterThanZeroHr = true;
                }

                if (!mFindFirstGreaterThanZeroHr) {
                    return;
                }

                mHrdatas.add(result.getIntValue());
            }
        }
    };

}
